<template>
  <a-modal
    v-model="isModalVisible"
    :mask-closable="false"
    class="partition-by"
    cancel-text="取消"
    ok-text="确定"
    @ok="onOk"
    @cancel="onCancel"
  >
    <template slot="title">
      分组排序新增列
      <a-tooltip
        title="rownumber（）函数，对数据进行分组，在组内数据进行排序并加上序号，新生成列的内容即为对应的序号"
      >
        <a-icon type="question-circle"></a-icon>
      </a-tooltip>
    </template>
    <a-form :form="form" :label-col="{ span: 6 }">
      <span style="color: rgba(0, 0, 0, 0.85);">分组对象：</span>
      <span class="tips-text">(提示：多个字段间为且的关系)</span>
      <div
        style="
          border: 1px solid #aaa;
          border-radius: 5px;
          margin: 12px 6px 18px;
          padding: 8px 18px;
        "
      >
        <a-form-item
          v-for="(groupObject, index) in groupObjectList"
          :key="index"
          :required="true"
          :label="`字段${index + 1}`"
          :label-col="{ span: 4 }"
        >
          <a-select
            v-model="groupObjectList[index]"
            size="small"
            class="select-form-item"
          >
            <a-select-option value=""> 请选择 </a-select-option>
            <a-select-option
              v-for="col in columnList"
              :key="col.name"
              :value="col.name"
              :disabled="validateDisabled(col.name)"
            >
              {{ col.name }}
            </a-select-option>
          </a-select>
          <a-button
            style="color: #52c41a;"
            type="link"
            icon="plus-circle"
            shape="circle"
            @click="() => addGroupObjectSelect(index)"
          ></a-button>
          <a-button
            style="color: #d9001b;"
            type="link"
            icon="minus-circle"
            shape="circle"
            @click="() => removeGroupObjectSelect(index)"
          ></a-button>
        </a-form-item>
      </div>
      <a-form-item label="排序对象">
        <a-select
          v-decorator="[
            'sortByCol',
            {
              rules: [{ required: true, message: '请选择排序对象!' }],
            },
          ]"
          placeholder="请选择"
          size="small"
          class="select-form-item"
        >
          <a-select-option v-for="col in columnList" :key="col.name">
            {{ col.name }}
          </a-select-option></a-select
        >
      </a-form-item>
      <a-form-item label="排序方式">
        <a-select
          v-decorator="[
            'orderByPolicy',
            {
              initialValue: 'ASC',
              rules: [{ required: true, message: '请选择排序方式!' }],
            },
          ]"
          size="small"
          class="select-form-item"
        >
          <a-select-option
            v-for="col in [
              { value: 'ASC', name: '升序' },
              { value: 'DESC', name: '降序' },
            ]"
            :key="col.key"
            :value="col.value"
          >
            {{ col.name }}
          </a-select-option></a-select
        >
      </a-form-item>
      <a-form-item label="新生成列名称">
        <a-input
          v-decorator="[
            'newColumn',
            {
              rules: [{ required: true, message: '请输入新列名!' }],
            },
          ]"
          size="small"
          class="select-form-item"
        ></a-input>
      </a-form-item>
    </a-form>
  </a-modal>
</template>

<script lang="ts">
import { Vue, Component, Prop, Watch } from 'vue-property-decorator'
import { IColumn, IKeyValueStore } from '@/store/modules/dataview'
import { StatisticsAction } from '@/util/data-selection-actions'

@Component
export default class PartitionBy extends Vue {
  @Prop() column!: IColumn
  @Prop() tableName!: string
  @Prop() taskId!: string
  @Prop() editData!: any
  @Prop({ default: false }) isEdit!: boolean
  @Prop({ default: '' }) parentTableName!: boolean
  @Prop({ default: [] }) columnList!: any
  private isModalVisible: boolean = true
  private groupObjectList: any = []
  private form: any

  beforeCreate() {
    this.form = this.$form.createForm(this, { name: 'filter_group_form' })
  }

  @Watch('column', { immediate: true, deep: true })
  private onColumnChange(newValue: IColumn) {
    this.groupObjectList.push(newValue.name)
    const indexArray = this.columnList.map((col: any) => {
      if (
        col.name.slice(0, 9) === 'newcolumn' &&
        !Number.isNaN(Number.parseInt(col.name.slice(9), 10))
      ) {
        return Number.parseInt(col.name.slice(9), 10) + 1
      }
      return 1
    })
    this.$nextTick(() => {
      this.form.setFieldsValue({
        newColumn: `newcolumn${Math.max(...indexArray)}`,
      })
    })
  }

  @Watch('editData', { immediate: true, deep: true })
  private onCurrentHistory(newValue: IKeyValueStore) {
    if (!newValue || !this.isEdit) {
      return
    }
    const history = newValue.data
    console.log(history)
    if (
      history.actionType === StatisticsAction.partitionBy &&
      history.col === this.column.name
    ) {
      this.$nextTick(() => {
        this.form.setFieldsValue({
          sortByCol: history.sortByCol,
          sortByPolicy: history.sortByPolicy,
          newColumn: history.newColumn,
        })
        this.groupObjectList = history.groupByCols
      })
    }
  }

  private async onOk() {
    this.form.validateFields(async (error: Error, values: any) => {
      if (this.groupObjectList.includes('')) {
        this.$message.error('请补充完分组对象')
        return
      }
      if (!error) {
        this.$emit('on-filter-params-change', {
          data: {
            action: 'PARTITION_AND_ORDER',
            col: this.form.getFieldValue('sortByCol'),
            description: `以${this.groupObjectList.join(
              '、'
            )}分类，以${this.form.getFieldValue('sortByCol')}排序`,
            actionType: StatisticsAction.partitionBy,
            groupByCols: this.groupObjectList,
            sortByCol: values.sortByCol,
            orderByPolicy: values.orderByPolicy,
            newColumn: values.newColumn,
          },
        })
        this.isModalVisible = false
      } else {
        console.log('error:', error)
      }
    })
  }

  onCancel() {
    this.$emit('on-filter-params-change', '')
    this.$emit('config-cancel')
    this.isModalVisible = false
  }

  private addGroupObjectSelect(index: number) {
    this.groupObjectList.splice(index + 1, 0, '')
  }

  private removeGroupObjectSelect(index: number) {
    if (this.groupObjectList.length === 1) {
      this.groupObjectList[0] = ''
      this.$forceUpdate()
    } else {
      this.groupObjectList.splice(index, 1)
    }
  }

  private validateDisabled(colName: any) {
    for (let i = 0; i < this.groupObjectList.length; i += 1) {
      if (colName === this.groupObjectList[i]) {
        return true
      }
    }
    return false
  }
}
</script>

<style lang="less" scoped>
.partition-by {
  height: 100%;

  .tips-text {
    color: #aaa;
    font-size: 13px;
    font-weight: 400;
  }

  .select-form-item {
    width: 280px;
  }

  /deep/ .ant-form-item {
    margin-bottom: 0;
  }

  /deep/ .ant-modal-body {
    padding: 12px 24px 24px;
  }
}
</style>
